/* eslint-disable @typescript-eslint/no-unsafe-call */
import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { CategoryDto } from './dto/category.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Category } from './entity/category.entity';
import { DeleteResult, Repository, UpdateResult } from 'typeorm';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private categoryRepository: Repository<Category>,
  ) {}

  async findAll(): Promise<Category[]> {
    return this.categoryRepository.find();
  }
  async findOneBy(data: any): Promise<Category | null> {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return this.categoryRepository.findOneBy(data);
  }
  async create(data: CategoryDto): Promise<any> {
    return this.categoryRepository.save(data);
  }

  async update(data: CategoryDto): Promise<any> {
    const category = await this.findOneBy({ id: data.id });
    if (!category) {
      throw new NotFoundException('类型不存在');
    }
    const result: UpdateResult = await this.categoryRepository.update(
      data.id,
      data,
    );
    if (result?.affected && result?.affected > 0) {
      return { message: '更新成功' };
    } else {
      throw new BadRequestException('更新失败');
    }
  }
  async delete(id: number): Promise<any> {
    const category = await this.findOneBy({ id });
    if (!category) {
      throw new NotFoundException('类型不存在');
    }
    const result: DeleteResult = await this.categoryRepository.delete(id);
    if (result?.affected && result?.affected > 0) {
      return { message: '删除成功' };
    } else {
      throw new BadRequestException('删除失败');
    }
  }
}
